package com.wu.common.utils;


import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class HttpPostUtil {
    URL url;
    HttpURLConnection conn;
    String boundary = "--------httppost123";
    Map<String, String> textParams = new HashMap();
    Map<String, File> fileparams = new HashMap();
    DataOutputStream ds;
    public static final String IMG_JPG = ".jpg";
    public static final String IMG_PNG = ".png";
    public static final String IMG_GIF = ".gif";
    public static final String IMG_BMP = ".bmp";

    public HttpPostUtil(String url) throws Exception {
        this.url = new URL(url);
    }

    public void setUrl(String url) throws Exception {
        this.url = new URL(url);
    }

    public void addTextParameter(String name, String value) {
        this.textParams.put(name, value);
    }

    public void addFileParameter(String name, File value) {
        this.fileparams.put(name, value);
    }

    public void clearAllParameters() {
        this.textParams.clear();
        this.fileparams.clear();
    }

    public byte[] send() throws Exception {
        this.initConnection();

        try {
            this.conn.connect();
        } catch (SocketTimeoutException var4) {
            throw new RuntimeException();
        }

        this.ds = new DataOutputStream(this.conn.getOutputStream());
        this.writeFileParams();
        this.writeStringParams();
        this.paramsEnd();
        InputStream in = this.conn.getInputStream();
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        int b;
        while((b = in.read()) != -1) {
            out.write(b);
        }

        this.conn.disconnect();
        return out.toByteArray();
    }

    private void initConnection() throws Exception {
        this.conn = (HttpURLConnection)this.url.openConnection();
        this.conn.setDoOutput(true);
        this.conn.setUseCaches(false);
        this.conn.setConnectTimeout(10000);
        this.conn.setRequestMethod("POST");
        this.conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + this.boundary);
    }

    private void writeStringParams() throws Exception {
        Set<String> keySet = this.textParams.keySet();
        Iterator it = keySet.iterator();

        while(it.hasNext()) {
            String name = (String)it.next();
            String value = (String)this.textParams.get(name);
            this.ds.writeBytes("--" + this.boundary + "\r\n");
            this.ds.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"\r\n");
            this.ds.writeBytes("\r\n");
            this.ds.writeBytes(this.encode(value) + "\r\n");
        }

    }

    private void writeFileParams() throws Exception {
        Set<String> keySet = this.fileparams.keySet();

        for(Iterator it = keySet.iterator(); it.hasNext(); this.ds.writeBytes("\r\n")) {
            String name = (String)it.next();
            File value = (File)this.fileparams.get(name);
            String valuename = value.getName();
            if (value.exists()) {
                this.ds.writeBytes("--" + this.boundary + "\r\n");
                this.ds.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + this.encode(valuename) + "\"\r\n");
                this.ds.writeBytes("Content-Type: " + this.getContentType(value) + "\r\n");
                this.ds.writeBytes("\r\n");
                this.ds.write(this.getBytes(value));
            } else {
                String myFilePath = value.getPath();
                if (myFilePath != null && myFilePath.startsWith("http")) {
                    byte[] netFileBytes = this.getURIFileBytes(myFilePath);
                    String lowerValueName = valuename.toLowerCase();
                    if (!lowerValueName.endsWith(".bmp") && !lowerValueName.endsWith(".gif") && !lowerValueName.endsWith(".jpg") && !lowerValueName.endsWith(".png")) {
                        valuename = System.currentTimeMillis() + this.getPicType(netFileBytes);
                    } else {
                        valuename = this.encode(valuename);
                    }

                    this.ds.writeBytes("--" + this.boundary + "\r\n");
                    this.ds.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + valuename + "\"\r\n");
                    this.ds.writeBytes("Content-Type: " + this.getContentType(value) + "\r\n");
                    this.ds.writeBytes("\r\n");
                    this.ds.write(netFileBytes);
                }
            }
        }

    }

    private byte[] getURIFileBytes(String url) throws IOException {
        url = url.replace("http:" + File.separator, "http://").replace("\\", "/");
        URL oracle = new URL(url);
        InputStream inStream = oracle.openStream();
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        boolean var6 = false;

        int len;
        while((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }

        inStream.close();
        return outStream.toByteArray();
    }

    private String getContentType(File f) throws Exception {
        ImageInputStream imagein = ImageIO.createImageInputStream(f);
        if (imagein == null) {
            return "application/octet-stream";
        } else {
            Iterator<ImageReader> it = ImageIO.getImageReaders(imagein);
            if (!it.hasNext()) {
                imagein.close();
                return "application/octet-stream";
            } else {
                imagein.close();
                return "image/" + ((ImageReader)it.next()).getFormatName().toLowerCase();
            }
        }
    }

    private byte[] getBytes(File f) throws Exception {
        FileInputStream in = new FileInputStream(f);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] b = new byte[1024];

        int n;
        while((n = in.read(b)) != -1) {
            out.write(b, 0, n);
        }

        in.close();
        return out.toByteArray();
    }

    private void paramsEnd() throws Exception {
        this.ds.writeBytes("--" + this.boundary + "--\r\n");
        this.ds.writeBytes("\r\n");
    }

    private String encode(String value) throws Exception {
        return URLEncoder.encode(value, "UTF-8");
    }

    public String getPicType(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder();
        if (src != null && src.length > 0) {
            for(int i = 0; i < 4; ++i) {
                int v = src[i] & 255;
                String hv = Integer.toHexString(v);
                if (hv.length() < 2) {
                    stringBuilder.append(0);
                }

                stringBuilder.append(hv);
            }

            String type = stringBuilder.toString().toUpperCase();
            if (type.contains("FFD8FF")) {
                return ".jpg";
            } else if (type.contains("89504E47")) {
                return ".png";
            } else if (type.contains("47494638")) {
                return ".gif";
            } else if (type.contains("424D")) {
                return ".bmp";
            } else {
                return "";
            }
        } else {
            return null;
        }
    }

    public static void main(String[] args) throws Exception {
        HttpPostUtil u = new HttpPostUtil("https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=i3um002Np_n-mgNVbPP9JEIfft7_hRq3eHE86slxI7Uh_5q0K5rFfLRnhD20HTCcFt92ulWnndpGlyiNgXi6UiWQqKxPCBsfYKmiY6Ws-isUVLaAFAXYO");
        u.addFileParameter("img", new File("C:/Users/zhangdaihao/Desktop/2.png"));
        byte[] b = u.send();
        String result = new String(b);
        System.out.println(result);
    }
}

